const router = require('koa-router')()
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');
const exec = require('child_process').exec;
const ffmpeg = require('fluent-ffmpeg');
const spawn = require('child_process').spawn;
const db = require('../db/initdb');

function together(imgPath, audioPath, outputPath) {
    return new Promise((resolve, reject) => {
        // const ffmpeg = spawn('ffmpeg', ['-r', 1, '-f', 'image2', '-loop', 1, '-i', imgPath, '-i', audioPath, '-s', '1920x1080', '-pix_fmt', 'yuvj420p', '-t', 5, '-vcodec', 'libx264', outputPath]);
        const ffmpeg = spawn('ffmpeg', ['-y', '-loop', 1, '-r', 1, '-i', imgPath, '-i', audioPath, '-vcodec', 'libx264', '-acodec', 'aac', '-shortest', outputPath])
        ffmpeg.on('close', (code) => {
            console.log(` ffmpeg exit with code ${code}`);

            resolve();
        })
    })
}


router.prefix('/imgvideo')

router.post('/together', async (ctx, next) => {
    console.log(ctx.query);
    const file = ctx.request.files.file // 获取上传的文件
    const fileName = `${Date.now()}.mp4` // 重命名文件
    // console.log(file);

    // 图片路径
    const imgPath = path.join(__dirname, `../public/images/${ctx.query.imgName}`);
    // 音频路径
    // const audioPath = path.join(__dirname, '../voice/岑宁儿-追光者.mp3');
    const audioPath = file.filepath;
    console.log("a: " + audioPath);
    // 输出文件路径
    const outputPath = path.join(__dirname, '../public/images', fileName);


    await together(imgPath, audioPath, outputPath)
        .then(() => {
            ctx.body = {
                code: 200,
                message: 'success',
                fileName: fileName
            };
        })
})

module.exports = router
